package com.hand.wfive.view

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.hand.wfive.R
import com.hand.wfive.adapter.DialogSignAdapter
import com.hand.wfive.entity.FileListModel
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FuncSwitchUtils
import com.hand.wfive.util.bottomShow
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssRequest
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import org.jetbrains.anko.find
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass

/**
 * （取消、确定）消息 Dialog
 */
class MsgDialog(
    context: Context,
    title: String,
    message: String,
    negativeText: String = "取消",
    positiveText: String = "确定",
    messageGravity: Int = Gravity.CENTER,
    negativeBg: Int = R.drawable.btn_dialog_msg_negative,
    positiveBg: Int = R.drawable.btn_dialog_msg_positive,
    event: (Int) -> Unit,
) : Dialog(context, R.style.CustomDialog) {
    init {
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setContentView(R.layout.dialog_msg)
        find<TextView>(R.id.tvTitle).text = title
        val msgView = find<TextView>(R.id.tvMsg)
        msgView.text = message
        msgView.gravity = messageGravity
        val negativeBtn = find<TextView>(R.id.tvNegative)
        negativeBtn.text = negativeText
        negativeBtn.setBackgroundResource(negativeBg)
        negativeBtn.singleClick {
            dismiss()
            event(0)
        }
        val positiveBtn = find<TextView>(R.id.tvPositive)
        positiveBtn.text = positiveText
        positiveBtn.setBackgroundResource(positiveBg)
        positiveBtn.singleClick {
            dismiss()
            event(1)
        }

        window?.setLayout(
            QMUIDisplayHelper.dp2px(context, 260),
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }
}

class MsgDialog2(
    context: Context,
    title: String,
    message: String,
    negativeText: String = "取消",
    positiveText: String = "确定",
    messageGravity: Int = Gravity.CENTER,
    negativeBg: Int = R.drawable.btn_dialog_msg_negative,
    positiveBg: Int = R.drawable.btn_dialog_msg_positive,
    event: (Int) -> Unit,
) : Dialog(context, R.style.CustomDialog) {
    init {
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setContentView(R.layout.dialog_msg2)
        find<TextView>(R.id.tv_title).text = title
        val msgView = find<TextView>(R.id.tv_message)
        msgView.text = message
        msgView.gravity = messageGravity
        val negativeBtn = find<TextView>(R.id.tv_negative)
        negativeBtn.text = negativeText
        negativeBtn.setBackgroundResource(negativeBg)
        negativeBtn.singleClick {
            dismiss()
            event(0)
        }
        val positiveBtn = find<TextView>(R.id.tv_positive)
        positiveBtn.text = positiveText
        positiveBtn.setBackgroundResource(positiveBg)
        positiveBtn.singleClick {
            dismiss()
            event(1)
        }

        window?.setLayout(
            QMUIDisplayHelper.dp2px(context, 260),
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }
}

/**
 * 输入框 Dialog
 */
class InputDialog(
    context: Context,
    title: String,
    hint: String = "请输入...",
    content: String = "",
    negativeText: String = "取消",
    positiveText: String = "确定",
    negativeBg: Int = R.drawable.btn_dialog_msg_negative,
    positiveBg: Int = R.drawable.btn_dialog_msg_positive,
    event: (Dialog, String) -> Unit,
) : Dialog(context, R.style.CustomDialog) {
    init {
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setContentView(R.layout.dialog_input)
        find<TextView>(R.id.tv_title).text = title
        val editText = find<EditText>(R.id.et_content)
        editText.setText(content)
        editText.hint = hint
        val negativeBtn = find<TextView>(R.id.tv_negative)
        negativeBtn.text = negativeText
        negativeBtn.setBackgroundResource(negativeBg)
        negativeBtn.singleClick { dismiss() }
        val positiveBtn = find<TextView>(R.id.tv_positive)
        positiveBtn.text = positiveText
        positiveBtn.setBackgroundResource(positiveBg)
        positiveBtn.singleClick { event(this, editText.text.toString()) }

        window?.setLayout(
            QMUIDisplayHelper.dp2px(context, 260),
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }
}

/**
 * 签字库/签章库
 */
class SignLibrarayDialog(
    context: Context, private val type: String, event: (String) -> Unit,
) :
    Dialog(context, R.style.CustomDialog) {

    private var mPage = 1
    private val mAdapter: DialogSignAdapter

    init {
        setContentView(R.layout.dialog_sign_lib)
        find<TextView>(R.id.tv_title).text =
            if (type == Params.fileTypeSign) "签字库" else "签章库"
        find<ImageView>(R.id.iv_close).singleClick { dismiss() }

        mAdapter = DialogSignAdapter(type)
        mAdapter.setOnItemClickListener { _, _, position ->
            if (NoFastClickUtils.isFastClick()) return@setOnItemClickListener
            dismiss()
            if (position == 0) {
                if (mAdapter.itemCount >= 2) event("needVip")
                else event("")
            } else {
                val funcType = if (type == Params.fileTypeSign) FuncSwitchUtils.FuncSign else FuncSwitchUtils.FuncStamp
                if (FuncSwitchUtils.canUse(funcType)) {
                    event(OssRequest.getInstance().getFileUrl(mAdapter.getItem(position).fileId))
                    FuncSwitchUtils.addUseCount(funcType)
                } else {
                    event("needVip")
                }
            }
        }
        val recyclerView = find<RecyclerView>(R.id.recycler_lib)
        recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        recyclerView.adapter = mAdapter
        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }
        loadData()

        bottomShow(false)
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

    private fun loadData() {
        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("type", type)
            .add("pageSize", 10)
            .add("page", mPage)
            .asClass<FileListModel>()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        val data = ArrayList<FileModel>()
                        data.add(FileModel())
                        if (it.data.records.isNotEmpty()) {
                            data.addAll(it.data.records)
                            mPage++
                        }
                        mAdapter.setList(data)
                        if (data.size == 1) {
                            mAdapter.loadMoreModule.loadMoreEnd(true)
                        } else {
                            mAdapter.loadMoreModule.loadMoreComplete()
                        }
                    } else if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd(true)
                    } else {
                        mAdapter.addData(it.data.records)
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }

                } else resetPage()
            }, {
                resetPage()
            })
    }
}